/**
 * 全局状态管理模块
 * 处理系统级别的全局状态
 */
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { RootState } from '../types';

// 全局状态接口
export interface GlobalState {
  isInitialized: boolean;
  notifications: number; 
  systemMessages: string[];
  lastUpdated: number;
}

// 初始状态
const initialState: GlobalState = {
  isInitialized: false,
  notifications: 0,
  systemMessages: [],
  lastUpdated: Date.now()
};

const globalSlice = createSlice({
  name: 'global',
  initialState,
  reducers: {
    setInitialized: (state, action: PayloadAction<boolean>) => {
      state.isInitialized = action.payload;
    },
    setNotifications: (state, action: PayloadAction<number>) => {
      state.notifications = action.payload;
    },
    incrementNotifications: (state) => {
      state.notifications += 1;
    },
    decrementNotifications: (state) => {
      if (state.notifications > 0) {
        state.notifications -= 1;
      }
    },
    clearNotifications: (state) => {
      state.notifications = 0;
    },
    addSystemMessage: (state, action: PayloadAction<string>) => {
      state.systemMessages.push(action.payload);
    },
    removeSystemMessage: (state, action: PayloadAction<string>) => {
      state.systemMessages = state.systemMessages.filter(msg => msg !== action.payload);
    },
    clearSystemMessages: (state) => {
      state.systemMessages = [];
    },
    updateTimestamp: (state) => {
      state.lastUpdated = Date.now();
    }
  }
});

export const { 
  setInitialized, 
  setNotifications, 
  incrementNotifications,
  decrementNotifications,
  clearNotifications,
  addSystemMessage,
  removeSystemMessage,
  clearSystemMessages,
  updateTimestamp
} = globalSlice.actions;

export default globalSlice.reducer;

// 选择器
export const selectIsInitialized = (state: RootState) => state.global.isInitialized;
export const selectNotifications = (state: RootState) => state.global.notifications;
export const selectSystemMessages = (state: RootState) => state.global.systemMessages;
export const selectLastUpdated = (state: RootState) => state.global.lastUpdated; 